<template>
  <div>
    <van-form>
      <van-cell-group inset>
        <van-field
          v-model="user.name"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="user.pwd"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <van-field
          class="left"
          v-model="user.captcha"
          name="验证码"
          label="验证码"
          placeholder="验证码"
          :rules="[{ required: true, message: '请填写验证码' }]"
        />
        <p class="yzm" v-html="yzm" @click="render()"></p>
      </van-cell-group>
      <div style="margin: 16px">
        <van-button
          @click="deng"
          round
          block
          type="primary"
          native-type="submit"
        >
          登录
        </van-button>
      </div>
    </van-form>
    <a href="/regest">立即注册</a>
  </div>
</template>

<script lang='ts' setup>
import { ref, reactive, onMounted } from "vue";
import { getcaptcha, login } from "../../api/api";
import { useRouter } from "vue-router";

const router = useRouter();

// 表单数据
const user = reactive({
  name: "",
  pwd: "",
  captcha: "",
});

// 验证码
const yzm = ref("");

onMounted(() => {
  render();
});

const render = () => {
  getcaptcha().then((res) => {
    yzm.value = res.data;
  });
};

const deng = () => {
  console.log(user);
  login(user).then((res) => {
    console.log(res);
    if (res.data.code == 1) {
      alert("用户名不存在 请先注册");
    }
    if (res.data.code == 2) {
      alert("密码不正确 请重新输入");
    }
    if (res.data.code == 0) {
      alert("验证码不一致 请重新输入");
    }
    if (res.data.code == 3) {
      let token = res.data.token;
      localStorage.setItem("token", token); //保存到本地存储中,可以将其作为过滤器使用。
      router.push("/home");
    }
  });
};
</script>

<style scoped>
.left {
  width: 230px;
  /* height: 50px; */
  float: left;
}
.yzm {
  /* float: right; */
}
</style>
